Puppet::Type.type(:openfire).provide(:openfire) do
	desc "Manages a openfire server"

	require "rexml/document"

	commands :wget => "/usr/bin/wget"
	commands :dpkg => "/usr/bin/dpkg"
	commands :aptremove => "/usr/bin/apt-get"

	#Constants
	OpenfireConfigFile = "/etc/openfire/openfire.xml"

	def exists?
		File.exists?("/etc/init.d/openfire")
	end

	def create
		debug "Trying to create a new Openfire server"
		begin
			link = resource[:link]
			wget ["-O", "/tmp/" + String(File.basename(link)), link]
			dpkg ["-i", "/tmp/" + String(File.basename(link))]
		rescue Puppet::ExecutionFailure
			debug "Impossible to create Openfire server. Openfire package can't be dowloaded or installed"
		end
	end

	def destroy
		debug "Trying to destroy openfire resource"
		package = File.basename(resource[:link], ".deb")
		aptremove ["remove", "--purge", package]
	end

	def setAttr(attrType, value)
		debug "Trying to set %s %s." % [typePort, value]
		begin
			xml = REXML::Document.new File.open(OpenfireConfigFile)
			if attrType == "port" or attrType == "secureport"
				xml.root.elements["adminConsole"].elements[attrType].text = value
			else
				xml.root.elements[attrType].text = value
			end

			formatter = REXML::Formatters::Default.new
			File.open(OpenfireConfigFile, 'w') do |result|
				formatter.write(xml, result)
			end
		rescue StandartError => e
			debug "Could not open %s" % OpenfireConfigFile
		end
	end

	def getAttr(attrType)
		begin
			xml = REXML::Document.new File.open(OpenfireConfigFile)
			if attrType == "port" or attrType == "secureport"
				return xml.root.elements["adminConsole"].elements["port"].text
			else
				return xml.root.elements[attrType].text = value
			end
		rescue StandartError => e
			debug "Could not open %s" % OpenfireConfigFile
		end
	end

	def port
		getAttr("port")
	end
	
	def port=(value)
		setAttr("port", value)
	end

	def secureport
		getAttr("secureport")
	end

	def secureport=(value)
		setAttr("secureport",value)
	end

	def locale
		getAttr("locale")
	end

	def locale=(value)
		setAttr("locale",value)
	end

	def interfaces
		# Not implemented yet
	end

	def interfaces=(value)
		# Not implemented yet
	end


end
